<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.teacherId }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>我的班级</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <!-- 搜索和添加区域-->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="8">
          <el-input placeholder="请输入班级名称查询" v-model="queryInfo.query" clearable @clear="getClasses">
            <el-button slot="append" icon="el-icon-search" @click="getClasses"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddClassDialog">添加班级</el-button>
        </el-col>
      </el-row>
      <!-- 班级列表 -->
      <el-table :data="classList" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="className" label="班级名称" width="180"></el-table-column>
        <el-table-column prop="teacherName" label="班主任" width="120"></el-table-column>
        <el-table-column label="学生人数" width="100">
          <template slot-scope="scope">
            {{ getStudentCount(scope.row.numberOfStudents) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditClassDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="success" icon="el-icon-user" @click="manageStudents(scope.row)">管理学生</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteClass(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 15px">
      </el-pagination>
    </el-card>
    
    <!-- 添加班级对话框-->  
    <el-dialog title="添加班级" :visible.sync="addClassDialogVisible" width="40%" @close="addClassDialogClosed">
      <el-form :model="addClassForm" :rules="addClassRules" ref="addClassFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="addClassForm.className"></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="teacherId">
          <el-select v-model="addClassForm.teacherId" placeholder="请选择班主任" style="width: 100%" :disabled="teacherSelectDisabled">
            <el-option v-for="teacher in teacherList" :key="teacher.teacherId" :label="teacher.name" :value="teacher.teacherId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addClassSubmit">确定</el-button>
      </span>
    </el-dialog>
    
    <!-- 编辑班级对话框-->  
    <el-dialog title="编辑班级" :visible.sync="editClassDialogVisible" width="40%" @close="editClassDialogClosed">
      <el-form :model="editClassForm" :rules="editClassRules" ref="editClassFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="editClassForm.className" disabled></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="teacherId">
          <el-select v-model="editClassForm.teacherId" placeholder="请选择班主任" style="width: 100%" :disabled="true">
            <el-option v-for="teacher in teacherList" :key="teacher.teacherId" :label="teacher.name" :value="teacher.teacherId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editClassDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editClassSubmit">确定</el-button>
      </span>
    </el-dialog>
    
    <!-- 班级学生管理对话框-->    
    <el-dialog title="班级学生管理" :visible.sync="manageStudentsDialogVisible" width="70%" @close="manageStudentsDialogClosed">
      <div v-if="currentClass">
        <h3>{{ currentClass.className }} - 学生管理</h3>
        
        <!-- 添加学生区域 -->
         <el-form :model="addStudentForm" :rules="addStudentRules" ref="addStudentFormRef" label-width="100px" style="margin-bottom: 20px">
          <el-form-item label="学生学号" prop="studentId">
            <el-input v-model="addStudentForm.studentId" placeholder="请输入学生学号" style="width: 300px">
              <el-button slot="append" icon="el-icon-plus" @click="addStudentToClass">添加</el-button>
            </el-input>
          </el-form-item>
        </el-form> 
        
        <!-- 批量添加学生区域 -->
        <el-form label-width="100px" style="margin-bottom: 20px">
          <el-form-item label="批量添加">
            <el-select v-model="selectedStudents" multiple placeholder="请选择多个学生添加到班级" style="width: 100%">
              <el-option v-for="student in availableStudents" :key="student.studentID" :label="`${student.studentID} - ${student.name}`" :value="student.studentID"></el-option>
            </el-select>
            <el-button type="primary" style="margin-top: 10px" @click="batchAddStudentsToClass">批量添加所选学生</el-button>
          </el-form-item>
        </el-form> 
        
        <!-- 班级学生列表 -->
        <el-table :data="classStudents" border stripe style="margin-top: 20px">
          <el-table-column type="index" label="#" width="50"></el-table-column>
          <el-table-column prop="studentID" label="学号" width="150"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="removeStudentFromClass(scope.row)">移出班级</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <el-pagination
          @size-change="handleStudentSizeChange"
          @current-change="handleStudentCurrentChange"
          :current-page="studentQueryInfo.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="studentQueryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="studentTotal">
        </el-pagination>
        
        <!-- 按钮区域 -->
        <div style="margin-top: 20px; text-align: right">
          <el-button @click="manageStudentsDialogVisible = false">关闭</el-button>
          <!-- <el-button type="primary" @click="viewClassStudents">查看完整学生列表</el-button> -->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        role: -1  // 默认初始化为-1，避免角色判断出错
      },
      teacherId: null,
      classList: [],
      teacherList: [],
      total: 0,
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      addClassForm: {
        className: '',
        teacherId: '',
        numberOfStudents: 0
      },
      editClassForm: {
        className: '',
        teacherId: '',
        numberOfStudents: 0
      },
      addClassDialogVisible: false,
      editClassDialogVisible: false,
      manageStudentsDialogVisible: false,
      currentClass: null,
      classStudents: [],
      availableStudents: [],
      selectedStudents: [],
      addStudentForm: {
        studentId: '',
        classId: ''
      },
      addClassRules: {
        className: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '请选择班主任', trigger: 'change' }
        ]
      },
      editClassRules: {
        teacherId: [
          { required: true, message: '请选择班主任', trigger: 'change' }
        ]
      },
      addStudentRules: {
        studentId: [
          { required: true, message: '请输入学生学号', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '学号必须为11位数字', trigger: 'blur' }
        ]
      },
      teacherSelectDisabled: false,
      studentQueryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      studentTotal: 0
    }
  },
  created() {
    // 从sessionStorage获取用户ID和角色，兼容两种存储方式
    // 方式1：直接从sessionStorage获取
    const storedId = window.sessionStorage.getItem('userID') // 修正key值为'userID'
    // 方式2：通过SessionManager获取
    const idFromManager = this.$sessionManager ? this.$sessionManager.getUserId() : null
    
    // 优先使用SessionManager中的值，其次使用sessionStorage中的值
    const userId = idFromManager || storedId
    
    if (userId) {
      // 确保teacherId是字符串类型
      this.teacherId = userId
      // console.log('用户ID:', this.teacherId, '类型:', typeof this.teacherId)
    } else {
      this.$message.error('用户ID不存在，请重新登录')
      this.$router.push('/')
      return
    }
    
    // 同样兼容两种方式获取用户角色
    const userRole = window.sessionStorage.getItem('userRole')
    const roleFromManager = this.$sessionManager ? this.$sessionManager.getUserRole() : null
    const role = roleFromManager || userRole
    
    if (role) {
      this.userInfo.role = parseInt(role)
      // console.log('用户角色:', this.userInfo.role)
      
      // 检查角色是否有权限访问此页面
      if (this.userInfo.role !== 0 && this.userInfo.role !== 1) {
        this.$message.warning('您没有权限访问此页面')
        this.$router.push('/manage/' + this.teacherId + '/video/list')
        return
      }
    } else {
      this.$message.error('用户角色不存在，请重新登录')
      this.$router.push('/')
      return
    }
    
    // 获取班级和教师列表
    this.getClasses()
    this.getTeachers()
  },
  methods: {
    // 获取班级列表
    async getClasses() {
      try {
        let url = ''
        const params = {}
        
        // 如果是管理员，获取所有班级
        if (this.userInfo.role === 0) {
          url = '/class/findAll'
          if (this.queryInfo.query.trim() !== '') {
            url = '/class/findByName'
            params.className = this.queryInfo.query
          }
        } else {
          // 如果是教师，只获取该教师的班级
          url = '/class/findByTeacher'
          params.teacherId = this.teacherId
          console.log('教师ID参数:', params.teacherId, '类型:', typeof params.teacherId)
          if (this.queryInfo.query.trim() !== '') {
            url = '/class/findByTeacherAndName'
            params.className = this.queryInfo.query
          }
        }
        
        // 添加分页参数
        params.pageNum = this.queryInfo.pageNum
        params.pageSize = this.queryInfo.pageSize
        
        const { data: res } = await this.$http.get(url, { params })
        console.log('班级查询响应:', res)
        
        if (res.code === 200) {
          // 处理分页数据
          this.classList = res.data.list || res.data || []
          this.total = res.data.total || this.classList.length || 0
          
          if (this.classList.length === 0) {
            this.$message.info('暂无班级信息')
            return
          }
          
          // 添加classId字段的兼容处理
          this.classList = this.classList.map(item => {
            // 确保每个班级对象有className和classId字段，使用小写来统一属性名
            if (item.ClassName && !item.className) {
              item.className = item.ClassName
            }
            if (item.ClassId && !item.classId) {
              item.classId = item.ClassId
            }
            return item
          })
          
          console.log('处理后的班级列表:', this.classList)
          
          // 获取每个班级的教师姓名
          for (let i = 0; i < this.classList.length; i++) {
            // const classItem = this.classList[i]
            // if (classItem.teacherID) {  
            //   try {
            //     const { data: teacherRes } = await this.$http.get('/user/query', {
            //       params: {
            //         id: classItem.teacherID
            //       }
            //     })
            //     if (teacherRes.code === 200 && teacherRes.data) {
            //       classItem.teacherName = teacherRes.data.name || '未知'
            //     } else {
            //       classItem.teacherName = '未知'
            //       console.warn('无法获取教师信息:', teacherRes)
            //     }
            //   } catch (error) {
            //     console.error('获取教师信息出错:', error)
            //     classItem.teacherName = '未知'
            //   }
            // } else {
            //   classItem.teacherName = '未指定'
            // }
          }
        } else if (res.code === 404 || res.code === 400) {
          // 用户不存在或没有班级或ID格式错误
          this.classList = []
          this.total = 0
          this.$message.warning(res.message || '没有找到相关班级信息')
        } else {
          this.$message.error(res.message || '获取班级信息失败：未知错误')
        }
      } catch (error) {
        console.error('获取班级列表出错:', error)
        if (error.response && error.response.status === 404) {
          this.$message.warning('用户信息不存在或未分配班级')
        } else {
          this.$message.error('获取班级信息失败：' + (error.message || '未知错误'))
        }
        this.classList = []
        this.total = 0
      }
    },
    // 获取教师列表
    async getTeachers() {
      try {
        // 如果是教师角色，只加载当前教师的信息
        if (this.userInfo.role === 1) {
          // 创建一个只包含当前教师的列表
          const { data: res } = await this.$http.get(`/teacher/query?teacherID=${this.teacherId}`)
          if (res.code === 200 && res.data) {
            this.teacherList = [{
              teacherId: res.data.teacherID, // 注意：后端返回字段是teacherID而不是id
              name: res.data.name || res.data.teacherID
            }]
          } else {
            //this.$message.warning('获取教师信息失败') 
            this.teacherList = []
          }
          return
        }
        
        // 管理员角色加载所有教师
        const { data: res } = await this.$http.get('/teacher/findAll')
        if (res.code === 200) {
          // 转换数据格式，确保有teacherId和name字段
          this.teacherList = res.data.map(teacher => ({
            teacherId: teacher.teacherID, // 修改为与后端一致的字段名
            name: teacher.name || teacher.teacherID
          }))
        } else {
          this.$message.error('获取教师列表失败')
        }
      } catch (error) {
        console.error('获取教师列表出错:', error)
        this.$message.error('获取教师列表失败')
      }
    },
    // 显示添加班级对话框
    showAddClassDialog() {
      this.addClassDialogVisible = true
      
      // 如果是教师角色，自动设置为自己，并禁用选择
      if (this.userInfo.role === 1) {
        this.addClassForm.teacherId = this.teacherId
        this.teacherSelectDisabled = true
        // 友好提示
        this.$notify({
          title: '班级管理提示',
          message: '作为教师，您创建的班级将自动以您作为班主任',
          type: 'info',
          duration: 5000,
          zIndex: 10000
        })
      } else {
        this.teacherSelectDisabled = false
      }
    },
    // 添加班级对话框关闭处理
    addClassDialogClosed() {
      this.$refs.addClassFormRef.resetFields()
    },
    // 提交添加班级
    addClassSubmit() {
      this.$refs.addClassFormRef.validate(async valid => {
        if (!valid) return
        try {
          // 获取当前登录教师的ID
          const currentTeacherId = this.userInfo.role === 1 ? this.teacherId : this.addClassForm.teacherId
          
          // 初始添加班级时，没有学生，创建空数组
          const studentIdsArray = [];
          
          const classData = {
            className: this.addClassForm.className,
            teacherID: currentTeacherId, // 教师ID - 与后端字段保持一致
            numberOfStudents: JSON.stringify(studentIdsArray) // 存储为JSON字符串格式
          }
          
          console.log('提交班级数据:', classData)
          
          const { data: res } = await this.$http.post('/class/insert', classData)
          if (res.code === 200) {
            this.$message.success('添加班级成功')
            this.addClassDialogVisible = false
            this.getClasses()
          } else {
            this.$message.error(res.message || '添加班级失败')
          }
        } catch (error) {
          console.error('添加班级出错:', error)
          console.error('错误详情:', error.response ? error.response.data : error.message)
          this.$message.error(`添加班级失败：${error.response ? error.response.data.message || '' : ''}`)
        }
      })
    },
    // 显示编辑班级对话框
    showEditClassDialog(row) {
      // 深拷贝行数据，避免直接修改表格数据
      this.editClassForm = JSON.parse(JSON.stringify({
        classId: row.classId || row.ClassId,
        className: row.className || row.ClassName,
        teacherId: row.teacherID || row.TeacherID,
        numberOfStudents: row.numberOfStudents || row.NumberOfStudents || 0
      }))
      
      this.editClassDialogVisible = true
      
      // 如果是教师角色，显示提示信息
      if (this.userInfo.role === 1) {
        if (this.teacherId !== this.editClassForm.teacherId) {
          this.$message.warning('您不是此班级的班主任，无法编辑')
          this.editClassDialogVisible = false
          return
        }
        
        // 友好提示
        this.$notify({
          title: '班级管理提示',
          message: '作为教师，您只能编辑自己班级的信息，且无法更改班主任',
          type: 'info',
          duration: 5000,
          zIndex: 10000
        })
      }
    },
    // 编辑班级对话框关闭处理
    editClassDialogClosed() {
      this.$refs.editClassFormRef.resetFields()
    },
    // 编辑班级
    async editClassSubmit() {
      this.$refs.editClassFormRef.validate(async valid => {
        if (!valid) return
        try {
          // 准备班级数据
          const classData = {
            classId: this.editClassForm.classId,
            className: this.editClassForm.className,
            teacherID: this.editClassForm.teacherId,
            numberOfStudents: this.editClassForm.numberOfStudents
          }
          
          // 准备请求参数
          const params = {}
          
          // 如果是教师角色，添加角色和教师ID参数
          if (this.userInfo.role === 1) {
            params.role = this.userInfo.role
            params.teacherId = this.teacherId
          }
          
          const { data: res } = await this.$http.put('/class/update', classData, { params })
          
          if (res.code === 200) {
            this.$message.success(res.message || '更新班级成功')
            this.editClassDialogVisible = false
            this.getClasses()
          } else {
            this.$message.error(res.message || '更新班级失败')
          }
        } catch (error) {
          console.error('编辑班级出错:', error)
          this.$message.error('更新班级失败')
        }
      })
    },
    // 删除班级
    deleteClass(row) {
      this.$confirm('确认删除该班级吗？此操作不会删除学生信息，但会解除学生与该班级的关联关系', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete('/class', {
            params: { className: row.className }
          })
          if (res.code === 200) {
            this.$message.success('删除班级成功')
            this.getClasses()
          } else {
            this.$message.error(res.message || '删除班级失败')
          }
        } catch (error) {
          console.error('删除班级出错:', error)
          this.$message.error('删除班级失败')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 打开管理学生对话框
    async manageStudents(classItem) {
      try {
        if (!classItem) {
          this.$message.warning('请选择班级')
          return
        }
        
        console.log('管理学生，班级信息', classItem)
        
        // 确保班级有classId
        if (!classItem.classId && classItem.className) {
          // 通过className查询班级classId
          try {
            const { data: res } = await this.$http.get('/class/getByName', {
              params: { className: classItem.className }
            })
            if (res.code === 200 && res.data) {
              classItem.classId = res.data.classId
              console.log('获取到班级ID:', classItem.classId)
            } else {
              this.$message.error(res.message || '获取班级ID失败')
              return
            }
          } catch (error) {
            console.error('获取班级ID失败:', error)
            this.$message.error('获取班级ID失败：' + (error.message || '未知错误'))
            return
          }
        }
        
        // 设置当前班级
        this.currentClass = classItem
        
        // 重置学生相关状态
        this.studentQueryInfo.pageNum = 1
        this.studentQueryInfo.pageSize = 10
        this.studentQueryInfo.query = ''
        this.classStudents = []
        this.selectedStudents = []
        this.newStudentForm = {
          studentID: '',
          name: '',
          gender: '男',
          phone: '',
          notes: ''
        }
        
        // 加载班级学生列表
        await this.getClassStudents()
        
        // 加载可添加的学生列表
        await this.getAvailableStudents()
        
        // 显示对话框
        this.manageStudentsDialogVisible = true
      } catch (error) {
        console.error('打开班级学生管理失败:', error)
        this.$message.error('打开班级学生管理失败')
      }
    },
    // 获取班级学生列表
    async getClassStudents() {
      try {
        console.log('获取班级学生列表，班级', this.currentClass)
        // 确保班级ID存在
        if (!this.currentClass || !this.currentClass.classId) {
          console.error('无法获取班级学生：班级ID为空')
          this.$message.warning('班级ID不能为空')
          return
        }
        
        // 确保classId为数字类型
        let classId = this.currentClass.classId
        if (typeof classId !== 'number') {
          classId = parseInt(classId)
          if (isNaN(classId)) {
            console.error('班级ID转换为数字失败', this.currentClass.classId)
            this.$message.error('班级ID格式错误')
            return
          }
        }
        
        console.log('班级ID:', classId, '类型:', typeof classId)
        
        // 获取班级信息
        const { data: classRes } = await this.$http.get(`/class/info/${classId}`)
        if (classRes.code !== 200) {
          this.$message.error('获取班级信息失败')
          return
        }
        
        // 解析学生数组
        let studentIds = []
        try {
          // 尝试多种字段名称可能的情况，兼容大小写问题
          const studentListStr = classRes.data.numberOfStudents || classRes.data.NumberOfStudents || '[]'
          console.log('班级学生列表原始数据:', studentListStr)
          studentIds = JSON.parse(studentListStr)
        } catch (e) {
          console.error('解析学生数组失败:', e)
          console.log('班级数据:', classRes.data)
          studentIds = []
        }
        
        if (studentIds.length === 0) {
          this.classStudents = []
          this.studentTotal = 0
          return
        }
        
        // 获取学生详细信息
        const { data: res } = await this.$http.post('/student/batchInfo', {
          studentIds: studentIds,
          pageNum: this.studentQueryInfo.pageNum,
          pageSize: this.studentQueryInfo.pageSize
        })
        
        console.log('班级学生列表响应:', res)
        if (res.code === 200) {
          this.classStudents = res.data.list || res.data || []
          this.studentTotal = res.data.total || studentIds.length || 0
          console.log('设置班级学生列表:', this.classStudents)
        } else {
          this.$message.warning(res.msg || '获取班级学生列表失败')
          console.error('获取班级学生列表失败，错误信息', res.msg)
          this.classStudents = []
        }
      } catch (error) {
        console.error('获取班级学生列表出错:', error)
        this.$message.error('获取班级学生列表出错')
        this.classStudents = []
      }
    },
    // 获取可以添加的学生列表（未分配班级或不在当前班级的学生）
    async getAvailableStudents() {
      try {
        const { data: res } = await this.$http.get('/student/findNoClass')
        if (res.code === 200) {
          this.availableStudents = res.data || []
        } else {
          this.$message.warning(res.message || '获取可添加学生列表失败')
          this.availableStudents = []
        }
      } catch (error) {
        console.error('获取可添加学生列表出错', error)
        this.$message.error('获取可添加学生列表失败')
        this.availableStudents = []
      }
    },
    // 向班级添加单个学生
    async addStudentToClass() {
      this.$refs.addStudentFormRef.validate(async valid => {
        if (!valid) return
        try {
          // 先查询学生是否存在 - 使用正确的API接口
          const { data: studentCheckRes } = await this.$http.get(`/student/query?studentID=${this.addStudentForm.studentId}`)
          if (studentCheckRes.code !== 200 || !studentCheckRes.data) {
            return this.$message.error('该学生不存在，请检查学号是否正确')
          }
          
          // 检查学生是否已在班级中
          if (studentCheckRes.data.classId && studentCheckRes.data.classId === this.currentClass.classId) {
            return this.$message.info('该学生已在本班级中')
          }
          
          // 获取班级信息以获取班级名称
          const { data: classRes } = await this.$http.get(`/class/info/${this.currentClass.classId}`)
          if (classRes.code !== 200) {
            return this.$message.error('获取班级信息失败')
          }
          
          // 使用正确的API更新学生班级信息
          const { data: updateRes } = await this.$http.put('/student/updateClass', {
            studentID: this.addStudentForm.studentId,
            className: classRes.data.className,
            classId: this.currentClass.classId
          })
          
          if (updateRes.code === 200) {
            this.$message.success('添加学生到班级成功')
            this.addStudentForm.studentId = ''
            // 刷新班级学生列表和可添加学生列表
            await this.getClassStudents()
            await this.getAvailableStudents()
            // 更新班级信息
            this.getClasses()
          } else {
            this.$message.error(updateRes.message || '添加学生到班级失败')
          }
        } catch (error) {
          console.error('添加学生到班级出错', error)
          this.$message.error('添加学生到班级失败：' + (error.message || '未知错误'))
        }
      })
    },
    // 批量添加学生到班级
    async batchAddStudentsToClass() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning('请选择要添加的学生')
        return
      }
      
      try {
        // 获取班级信息以获取班级名称
        const { data: classRes } = await this.$http.get(`/class/info/${this.currentClass.classId}`)
        if (classRes.code !== 200) {
          return this.$message.error('获取班级信息失败')
        }
        
        // 使用正确的API更新学生班级信息
        const promises = this.selectedStudents.map(studentId => {
          return this.$http.put('/student/updateClass', {
            studentID: studentId,
            className: classRes.data.className,
            classId: this.currentClass.classId
          })
        })
        
        const results = await Promise.all(promises)
        const successCount = results.filter(res => res.data.code === 200).length
        
        if (successCount === this.selectedStudents.length) {
          this.$message.success(`成功添加 ${successCount} 名学生到班级`)
        } else if (successCount > 0) {
          this.$message.warning(`成功添加 ${successCount} 名学生到班级，${this.selectedStudents.length - successCount} 名添加失败`)
        } else {
          this.$message.error('批量添加学生到班级失败')
        }
        
        // 重置选择
        this.selectedStudents = []
        
        // 刷新班级学生列表和可添加学生列表
        await this.getClassStudents()
        await this.getAvailableStudents()
        
        // 更新班级信息
        this.getClasses()
      } catch (error) {
        console.error('批量添加学生到班级出错', error)
        this.$message.error('批量添加学生到班级失败：' + (error.message || '未知错误'))
      }
    },
    // 从班级移除学生
    async removeStudentFromClass(student) {
      this.$confirm(`确认将学生 ${student.name}(${student.studentID}) 移出班级吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          console.log('移除学生:', student)
          
          // 获取当前班级信息
          const { data: classRes } = await this.$http.get(`/class/info/${this.currentClass.classId}`)
          if (classRes.code !== 200) {
            return this.$message.error('获取班级信息失败')
          }
          
          // 跳过班级学生列表检查，直接调用后端接口移除学生
          console.log(`直接移除学生 ${student.studentID} 从班级 ${this.currentClass.classId}`)
          
          // 如果班级列表中有该学生，直接使用后端接口处理
          // 不需要在前端手动检查学生是否在班级中
          
          // 使用学生接口更新学生班级信息(设置为空)
          // 这将自动更新班级学生列表和学生记录
          console.log(`移除学生 ${student.studentID} 从班级 ${this.currentClass.classId}`)
          
          const { data: updateRes } = await this.$http.put('/student/updateClass', {
            studentID: student.studentID,
            className: null,  // 设置为null移除学生班级
            classId: null    // 设置为null移除学生班级
          })
          
          if (updateRes.code === 200) {
            this.$message.success('已将学生移出班级')
            // 刷新班级学生列表和可添加学生列表
            await this.getClassStudents()
            await this.getAvailableStudents() 
            // 更新班级信息
            this.getClasses()
          } else {
            this.$message.error(updateRes.message || '移除学生失败')
          }
        } catch (error) {
          console.error('移出学生出错:', error)
          this.$message.error('移出学生失败：' + (error.message || '未知错误'))
        }
      }).catch(() => {
        this.$message.info('已取消移出操作')
      })
    },
    // 管理学生对话框关闭处理
    manageStudentsDialogClosed() {
      this.currentClass = null
      this.classStudents = []
      this.availableStudents = []
      this.selectedStudents = []
      this.addStudentForm.studentId = ''
    },
    
    // 计算学生人数
    getStudentCount(studentListStr) {
      try {
        if (!studentListStr) return 0
        
        // 如果是字符串，尝试解析JSON
        if (typeof studentListStr === 'string') {
          const students = JSON.parse(studentListStr)
          return Array.isArray(students) ? students.length : 0
        }
        
        // 如果已经是数组
        if (Array.isArray(studentListStr)) {
          return studentListStr.length
        }
        
        return 0
      } catch (e) {
        console.error('计算学生人数出错:', e)
        return 0
      }
    },
    // 查看完整学生列表
    viewClassStudents() {
      // 保存当前班级信息到sessionStorage
      sessionStorage.setItem('currentClass', JSON.stringify(this.currentClass))
      // 跳转到班级学生页面
      this.$router.push('/manage/' + this.teacherId + '/class/students')
    },
    // 每页显示条数改变
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getClasses()
    },
    // 当前页改变
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getClasses()
    },
    // 学生列表每页显示条数改变
    handleStudentSizeChange(newSize) {
      this.studentQueryInfo.pageSize = newSize
      this.getClassStudents()
    },
    // 学生列表当前页改变
    handleStudentCurrentChange(newPage) {
      this.studentQueryInfo.pageNum = newPage
      this.getClassStudents()
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
